package cn.wygandwdn.core.transport.server.handler;

import cn.wygandwdn.common.message.RpcRequest;
import cn.wygandwdn.common.message.RpcResponse;
import cn.wygandwdn.core.registry.ServiceProvider;
import cn.wygandwdn.core.registry.impl.ServiceProviderImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @description:
 * @author: WYG
 * @time: 2021/10/28 19:58
 */

public class RequestHandler {

    private static final Logger log = LoggerFactory.getLogger(RequestHandler.class);

    private static final ServiceProvider provider;
    static {
        provider = new ServiceProviderImpl();
    }

    public RpcResponse handle(RpcRequest request) {
        String serviceName = request.getServiceName();
        Object service = provider.getService(serviceName);
        return invokeTargetMethod(request, service);
    }

    private RpcResponse invokeTargetMethod(RpcRequest rpcRequest, Object service) {
        Object result = null;
        log.debug("request: {}, service: {}", rpcRequest, service);
        try {
            Method method = service.getClass().getMethod(rpcRequest.getMethodName(), rpcRequest.getParametersTypes());
            result = method.invoke(service, rpcRequest.getParameters());
            log.debug("服务: {} 成功调用方法: {}", rpcRequest.getInterfaceName(), rpcRequest.getMethodName());
        } catch (InvocationTargetException | NoSuchMethodException | IllegalAccessException e) {
            log.error("调用过程出错: {}", e.getMessage());
            return RpcResponse.fail(rpcRequest.getSequenceId(), e);
        }
        return RpcResponse.success(rpcRequest.getSequenceId(), result);
    }
}
